<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Sinalogin
 *
 * @author Administrator
 */
class Sinalogin extends ThirdPartyLogin{
    const GET_AUTH_CODE_URL = "https://api.weibo.com/oauth2/authorize";
    const GET_ACCESS_TOKEN_URL = "https://api.weibo.com/oauth2/access_token";
    const GET_OPENID_URL = "https://api.weibo.com/oauth2/get_token_info";
    private $app_key;
    private $app_secret;
    private $redirect_uri;
    private $scope;
    private $state;
    private $settingLogic;
    public function __construct() {
        parent::__construct();
        $this->settingLogic=  $this->load("setting");
        $db=$this->settingLogic->get_one("option_value", "option_key='SINA_APP_KEY'");
        $db2=$this->settingLogic->get_one("option_value", "option_key='SINA_APP_SECRET'");
        $db3=$this->settingLogic->get_one("option_value", "option_key='SINA_REDIRECT_URI'");
        $this->app_key=$db["option_value"];
        $this->app_secret=$db2["option_value"];
        $this->redirect_uri=  urlencode($db3["option_value"]);
        $this->scope="all";
    }
     //sina快捷登录
    public function login(){
         $this->state="sinalogin".uniqid(rand(), TRUE);
         $_SESSION["SINA_state"]=  $this->state;
         $url= self::GET_AUTH_CODE_URL."?client_id={$this->app_key}&redirect_uri={$this->redirect_uri}&state={$this->state}&scope={$this->scope}";
         header("Location:{$url}");
    }
    
    //回调地址
    public function callback(){
        if($_SESSION["SINA_state"]!=$_GET['state']){
            $this->showError("30001");
        }
         $keysArr = array(
            "grant_type" => "authorization_code",
            "client_id" => $this->app_key,
            "redirect_uri" =>  $this->redirect_uri,
            "client_secret" =>  $this->app_secret,
            "code" => $_GET['code']
        );
   
       $url=  $this->combineURL(self::GET_ACCESS_TOKEN_URL, $keysArr);
       //$response=  Common::Get_Contents($url);
       $response=Common::Curl_Post($url, $keysArr);
       $token=  json_decode($response,true);
       if ( is_array($token) && !isset($token['error']) ) {
			$_SESSION["sina_access_token"]= $token['access_token'];
                        $_SESSION["sina_uid"]=$token['uid'];
			//$this->refresh_token = $token['refresh_token'];
		} else {
                        $this->showError($token['error'], "get access token failed." . $token['error']);
			
        }
        $this->get_token_info();
        $user=$this->get_user_info();
        $this->SaveToTenant($user);
        echo "<script>window.opener.location.href='".Common::RewriteUrl("Tenantadmin","index")."';window.close();</script>";
        
    }
    //get token info查询用户access_token的授权相关信息，包括授权时间，过期时间和scope权限。
    public function get_token_info(){
         //-------请求参数列表
        $keysArr = array(
            "access_token" => $_SESSION["sina_access_token"]
        );

        $graph_url = $this->combineURL(self::GET_OPENID_URL, $keysArr);
        $response=Common::Curl_Post($graph_url, $keysArr);
        $uinfo=  json_decode($response,true);
        $_SESSION["sina_uid"]=$uinfo["uid"];
    }
    //根据用户ID获取用户信息
    private function get_user_info(){
        $url="https://api.weibo.com/2/users/show.json";
        $keysArr = array(
            "source" => $this->app_key,
            "access_token"=> $_SESSION["sina_access_token"],
            "uid"=>$_SESSION["sina_uid"]
        );
        $url=$this->combineURL($url, $keysArr);
        $response= json_decode(Common::Get_Contents($url),true);
        
        return $response;
    }
    
    //把qq资料当成租户信息保存到租户表
    public function SaveToTenant($user){
        $tenantLogic=  $this->load("tenant");
        $cityLogic=  $this->load("city");
        $provinceLogic=  $this->load("province");
        if($user){
            $password=  md5($user["id"]);
            $exist=$tenantLogic->get_one("*", "((user_name='{$user["id"]}' and password='{$password}') or third_uid='{$user["id"]}') and status=1");
            if(!$exist){
                
             $w=PinYin::cn_explode(Common::strEscape($user["screen_name"]));
             $zimu="";
             foreach ($w as $v){
                    $zimu.= PinYin::to_first($v) ;
             }
                $local=  explode(" ", $user["location"]);
                 $tenantinfo=array(
                     "base_name"=>$user["screen_name"],
                     "user_name"=>$user["id"],
                     "password"=>$password,
                     "sex"=>$user["gender"]=="f"?2:1,
                     "create_time"=>  time(),
                     "last_login_ip"=>  Common::getIp(),
                     "city"=>isset($local[1])?$local[1]:"",
                     "province"=>  isset($local[0])?$local[0]:"",
                     "last_login_time"=>  time(),
                     "status"=>  1,
                     "is_third"=>1,
                     "sx"=>$zimu,
                     "third_uid"=>$user["id"],
                     "pinyin"=>  PinYin::utf8_to(Common::strEscape($user["screen_name"]))
                 );   
                 if(isset($local[0])){
                      $province=  $provinceLogic->get_one("*", "province like '{$local[0]}%'");
                      if($province)
                      $tenantinfo["province_id"]=$province["id"];
                 }
                 if(isset($local[1])){
                      $city=  $cityLogic->get_one("*", "city like '{$local[1]}%'");
                      if($city)
                      $tenantinfo["city_id"]=$city["id"];
                 }
                 $tid=$tenantLogic->insert($tenantinfo,TRUE);
                 if($user["avatar_large"]){
                     $image_url=  urlencode($user["avatar_large"]);
                     $this->runThread(Common::RewriteUrl("Sinalogin", "savetouxiang")."?tid={$tid}&tx={$image_url}");
                   // $image=  $this->upload->save_image($user->figureurl_qq_2);
                }elseif($user["profile_image_url"]){
                    $image_url=  urlencode($user["profile_image_url"]);
                    $this->runThread(Common::RewriteUrl("Sinalogin", "savetouxiang")."?tid={$tid}&tx={$image_url}");
                    //$image=  $this->upload->save_image($user->figureurl_qq_1);
                }
            }else{
                 $tenantinfo=array(
                    "last_login_ip"=>  Common::getIp(), 
                    "last_login_time"=>  time(),
                    "third_uid"=>$user["id"]
                  );
                  $tenantLogic->update($tenantinfo, "id={$exist["id"]}");
            }
            
            
            $tenant=$tenantLogic->get_one("*", "((user_name='{$user["id"]}' and password='{$password}') or third_uid='{$user["id"]}') and status=1");
             $_SESSION["tenant_info"]=$tenant;
             setcookie("tenant_info", serialize($tenant), time()+3600*24,"/");
        }
    }
    
    public function savetouxiang(){
        $tid=isset($_REQUEST["tid"])?intval($_REQUEST["tid"]):0;
        $touxiang=  isset($_REQUEST["tx"])?$_REQUEST["tx"]:"";
        if($touxiang&&$tid){
              $tenantLogic=  $this->load("tenant");
              $image=  $this->upload->save_image($touxiang);
              $data=array(
                  "image"=>$image
              );
              $tenantLogic->update($data,"id={$tid}");
              
        }
    }
}
